package com.zym.application.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zym.application.Main;
import com.zym.application.config.SystemConfig;
import com.zym.application.controller.IndexController;
import com.zym.application.exception.AppBugExcepiton;
import com.zym.application.utils.LogUtils;
import com.zym.application.utils.StringUtils;
import com.zym.framework.alert.AlertUtils;
import com.zym.framework.utlis.FxmlUtil;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

import java.awt.*;


/**
 * QQ 165149324
 * 臧英明
 * 页面管理服务类
 * @author
 * @create 2021-02-03
 */
public class PageService {
    private  Parent loginRoot ;
    private  Parent indexRoot;
    private  Scene loginScene;
    private WebView webView;
    private WebEngine webEngine;

    private  Scene indexScene;
    private  Stage mainStage;
    private Dimension screensize   =   Toolkit.getDefaultToolkit().getScreenSize();
    private static PageService pageController;
    private String windowsName = "login";
    private WinMainInfo LoginMainInfo = new WinMainInfo();
    private WinMainInfo IndexMainInfo = new WinMainInfo();
    /**
     * 获取主窗口信息
     * @return
     */
    public WinMainInfo getWinMainInfo(){
        WinMainInfo winMainInfo = new WinMainInfo();
        if(windowsName.equals("index")){
           return IndexMainInfo;
        }else {
           return LoginMainInfo;
        }
    }

    private PageService(Stage stage){
        mainStage = stage;
        //加载Web视图
        webView = new WebView();

        webEngine = webView.getEngine();
        ScrollPane scrollPane = new ScrollPane();
        scrollPane.setContent(webView);


        //加载图标
        stage.getIcons().add(new Image(Main.class.getResourceAsStream("/static/logo.jpg")));

        loginRoot = FxmlUtil.loadFxmlFromResource("/view/login.fxml").getRoot();
        indexRoot =  FxmlUtil.loadFxmlFromResource("/view/index.fxml").getRoot();

        //加载UI
//        String s = Main.class.getResource("/component/css/main.css").toExternalForm();
//        loginRoot.getStylesheets().add(s);
//        indexRoot.getStylesheets().add(s);

        loginScene = new Scene(loginRoot, 600, 400);
        int width = (int)(screensize.getWidth() * 0.83);
        int height = (int)(screensize.getHeight() * 0.83);
        LogUtils.println("设置组件分辨率高:"+height+" 宽:" +width);
        indexScene = new Scene(indexRoot, width, height);




        IndexMainInfo.setHeight(indexScene.getHeight());
        IndexMainInfo.setWidth(indexScene.getWidth());
        IndexMainInfo.setX(indexScene.getX());
        IndexMainInfo.setY(indexScene.getY());
        IndexMainInfo.setWindow(mainStage);

        LoginMainInfo.setWindow(mainStage);
        LoginMainInfo.setHeight(loginScene.getHeight());
        LoginMainInfo.setWidth(loginScene.getWidth());
        LoginMainInfo.setX(loginScene.getX());
        LoginMainInfo.setY(loginScene.getY());
        //窗口监听
        mainStage.xProperty().addListener(new ChangeListener<Number>() {
            @Override
            public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
                LoginMainInfo.setX(newValue.doubleValue());
            }
        });
        mainStage.yProperty().addListener(new ChangeListener<Number>() {
            @Override
            public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
                LoginMainInfo.setY(newValue.doubleValue());
            }
        });
        loginScene.widthProperty().addListener(new ChangeListener<Number>() {
            @Override
            public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
                LoginMainInfo.setWidth(newValue.doubleValue());
            }
        });
        loginScene.heightProperty().addListener(new ChangeListener<Number>() {
            @Override
            public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
                LoginMainInfo.setHeight(newValue.doubleValue());
            }
        });

    }

    public static PageService init(Stage stage){
        if(pageController == null){
            pageController =  new PageService(stage);
        }
        return pageController;
    }
    public static PageService getInstance(){
        if(pageController == null){
           throw new AppBugExcepiton("pageController not init");
        }
        return pageController;
    }

    public Stage getMainStage() {
        return mainStage;
    }

    public  void loadMenu(JSONArray menuData) {
        for (int i = 0; i <menuData.size() ; i++) {
            JSONObject jsonObject = menuData.getJSONObject(i);
            if(jsonObject.getString("URL").equals("Tms")){
                JSONArray children = jsonObject.getJSONArray("children");
                parseMenuJSON(children);
                return;
            }
        }
    }

    private  void parseMenuJSON(JSONArray root){
        IndexController indexController = FxmlUtil.getCacheController("/view/index.fxml", IndexController.class);
        ObservableList<Menu> menus = indexController.getMenuBar().getMenus();
        for (int i = 0; i <root.size() ; i++) {
            JSONObject jsonObject = root.getJSONObject(i);
            Menu menu = new Menu();
            menu.setText(jsonObject.getString("TITLE"));
            menu.setId(jsonObject.getString("ID"));
            menus.add(menu);
            JSONArray children = jsonObject.getJSONArray("children");
            if(children!= null && children.size() != 0){
                ObservableList<javafx.scene.control.MenuItem> items = menu.getItems();
                for (int j = 0; j <children.size() ; j++) {
                    JSONObject jsonObject1 = children.getJSONObject(j);
                    MenuItem menuItem = new MenuItem();
                    menuItem.setText(jsonObject1.getString("TITLE"));
                    menuItem.setId(jsonObject1.getString("ID"));
                    menuItem.setOnAction((ActionEvent e) -> {
                        addTable(jsonObject1.getString("COMPONENT"),jsonObject1.getString("TITLE"));
                    });
                    items.add(menuItem);
                }
            }
        }
    }

    public  void goLogin(){
        String loginName = SystemConfig.getInstance().getLoginName();
        mainStage.setTitle(loginName);
        mainStage.setScene(loginScene);
        int width = (int)(screensize.getWidth() * 0.1);
        int height = (int)(screensize.getHeight() * 0.5);
        mainStage.setY(width);
        mainStage.setX(height);
        mainStage.show();
        windowsName = "login";
    }
    public  void goIndex(){
        goIndex(null);
    }
    public  void goIndex(String title){
        if(StringUtils.isNotEmpty(title)){
            mainStage.setTitle(title);
        }else {
            mainStage.setTitle("物流云TMS");
        }
        mainStage.setY(15);
        mainStage.setX(15);
        mainStage.setScene(indexScene);
        mainStage.show();
        windowsName = "index";
    }

    /**
     * 添加面板~
     * @param tabName
     */
    public void addTable(String tabName,String titleName) {
        TabPane tabPane = FxmlUtil.getCacheController("/view/index.fxml", IndexController.class).getTabPane();
        String XMLPath = "/"+tabName+".fxml";
        //如果存在则不添加 聚焦
        Tab tab = null;
        ObservableList<Tab> tabs = tabPane.getTabs();
        for (int i = 0; i <tabs.size() ; i++) {
            Tab forTabl = tabs.get(i);
            if(XMLPath.equals(forTabl.getId())){
                tab = forTabl;
                break;
            }
        }
        if(tab != null){//聚焦
            tabPane.getSelectionModel().select(tab);
        }else {//加载
            Tab newTab = new Tab();
            FXMLLoader load = load(XMLPath);//获取面板
            Parent root = load.getRoot();
            newTab.setId(XMLPath);
            newTab.setContent(root);
            newTab.setText(titleName);
            tabs.add(newTab);
            tabPane.getSelectionModel().select(newTab);
            //聚焦
        }

    }

    /**
     * 加载table
     * @param XMLPath
     */
    private FXMLLoader load(String XMLPath){
        FXMLLoader cacheLoader = FxmlUtil.getCacheLoader(XMLPath);
        if(cacheLoader != null){
          return cacheLoader;
        }
        try {
            return  FxmlUtil.loadFxmlFromResource(XMLPath);
        }catch (IllegalStateException es){
            AlertUtils.error("错误，此模块未开发或未开放，请查看B/S端");
        }
        return null;

    }

    public void goWeb(String url){
        webEngine.load(url);
    }

    public WebView getWebView() {
        return webView;
    }
}
